var mongodb = require('./db');

function Post (username, post, time) {
	this.user = username;
	this.post = post;
	if(time){
		this.time = time;
	}else{
		var date = new Date();
		var year = date.getFullYear();  
		var month = date.getMonth() + 1;  
		var day = date.getDate(); 

		if (month < 10) month = '0' + month;  
		if (day < 10) day = '0' + day;  

		var hour = date.getHours();  

		if (hour < 10) {  
			hour = '0' + hour;  
		}  
		var minute = date.getMinutes();  
		if (minute < 10) {  
			minute = '0' + minute;  
		}  
		var second = date.getSeconds();  
		if (second < 10) {  
			second = '0' + second;  
		}  

		this.time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	}
}

module.exports = Post;

Post.prototype.save = function save(callback) {
	//存入mongoDB的文档
	var post = {
        user : this.user,
		post : this.post,
		time : this.time
    };
	mongodb.open(function(err, db){
		if(err){
			return callback(err);
		} 
		
		//读取posts集合
		db.collection('posts', function(err, collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			//为user属性添加索引
			collection.ensureIndex({"user":1,'_id':-1},{
				"unique":true
				},{w: 0});     
			collection.insert(post,{safe: true}, function(err, posts){
				mongodb.close();
				callback(err, posts);
			});
				
		});
	});
};

Post.get = function get(username, callback){
	mongodb.open(function(err, db){
		if(err){
			return callback(err);
		}
		//读取posts集合
		db.collection('posts', function(err, collection){
			if(err){
				mongodb.close();
				return callback(err);
			}

			//查找user属性为username的文档，如果username是null则匹配全部
			var query = {};
			if(username){
				query.user = username;
			}
			/*
			collection.findOne(query, function(err, docs){
				mongodb.close();
				if(err){
					callback(err, null);
				}
				var posts = [];
				for(i in docs){
					posts.push(docs[i]);
				}
				posts.length = 3;
				callback(null,posts);
			});
			*/
			collection.find(query).sort({time: -1}).toArray(function(err, docs){
				mongodb.close();
				if(err){
					console.log("是是是是否啊"+err)
					callback(err, null);
				}
				//封装posts为Post对象
				var posts = [];
				for(i in docs){
					posts.push(docs[i]);
				}
				callback(null, posts);
			})
		});
	});
};